import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { DomSanitizer } from '@angular/platform-browser';
import { ApiService } from '@core/api.service';
import { DatePipe } from '@angular/common';
import { ControlApiService } from '@core/controlApi.service';
import { StationDevtypeService } from '@core/stationDevtype.service';
import { Router } from '@angular/router';
import { _HttpClient } from '@delon/theme';
import { TreeTools } from '@core/treeTools.tool';
import { environment } from '../../../../environments/environment';

@Component({
    selector: 'app-controldetail',
    templateUrl: './detail.component.html',
    styleUrls: ['./detail.component.less']
})

export class ControldetailComponent implements OnInit {
    // wzjyData: any = [{ id: '' }];
    jxjlData: any = [];
    wtjlData: any = [];
    bjalData: any = [];
    gzxxData: any = [];

    stationSelect: any = [];
    devTypeSelect: any = [];
    alarmTypeSelect: any = [];
    stepNameSelect: any = [];

    selectedIndex = 1;
    czjyAlarmType = '';
    // wtkVisible = false;
    // dwVisible = false;
    // prVisible = false;
    // wtkIframe: any;
    mnlIframe: any;
    dwIframe: any;
    prIframe: any;
    queryParams: any = {};
    stationId = '';
    devTypeIf = true;
    devTypeId = '';
    alarmTypeIf = true;
    alarmTypeId = '';
    stepNameId = '';
    devNameText = '';
    devNameId = '';
    sjNameText = '';
    themeClass = 'whitetheme';
    selectClass = 'defaultSelect';
    tabBarStyle = { 'margin': '0 4px 5px 4px', 'text-align': 'center', 'color': '#000' };
    treeNodeStyle = { 'max-width': '300px', 'max-height': '400px', 'overflow-y': 'auto', 'overflow-x': 'hidden' };
    devTreeNodes = [];

    constructor(
        private apiService: ApiService,
        private message: NzMessageService,
        private sanitizer: DomSanitizer,
        private datePipe: DatePipe,
        private controlApiService: ControlApiService,
        private statdevtype: StationDevtypeService,
        private http: _HttpClient,
        public treeTools: TreeTools,
        private router: Router
    ) { }

    ngOnInit() {
        this.selectedIndex = 0;
        window.addEventListener('message', (data) => {
            if (data.data && data.data !== 'undefined' && JSON.stringify(data.data).indexOf('webpackOk') === -1) {
                this.devNameText = data.data;
                this.devNameId = '';
                // 设备类型
                this.getdevtype();
                // 设备检修记录表
                this.getWorkByDevName();
                // 设备问题记录表
                this.getProbByDevname();
                // 同类型报警案例表
                this.listByBjlx();
                // 设备历史故障信息表
                this.listByCz();
            }
        }, false);
        this.sjNameText = this.datePipe.transform(new Date(), 'yyyy-MM-dd HH:mm:ss');
        const beginDate = this.datePipe.transform(new Date(this.sjNameText).getTime() - 1 * 15 * 60 * 1000, 'yyyy-MM-dd HH:mm:ss');
        const endDate = this.datePipe.transform(new Date(this.sjNameText).getTime() + 1 * 10 * 60 * 1000, 'yyyy-MM-dd HH:mm:ss');
        // 车站名称
        this.statdevtype.getStation((resdata) => {
            this.stationId = 'KMBUR_KMNSEG_STA_19';
            this.stationSelect = this.treeTools.formatTreeNode(resdata);
            // 设备类型（包含设备名称接口）
            this.getAllTypesByStaId(this.stationId);
            this.mnlIframe = this.sanitizer.bypassSecurityTrustHtml(
                `<iframe src="/csmis/staht/HTtest.jsp?` +
                `setZoom=1.5&staId=${this.stationId}&beginDate=${beginDate}&endDate=${endDate}"` +
                `frameborder="0" style="width:1876px;height:610px;position:absolute;z-index:9;">
                        </iframe>`
            );
        });

        // 处置流程
        this.controlApiService.menuProcess().subscribe((res: any) => {
            for (const item of res) {
                this.stepNameSelect.push({
                    id: item.cid,
                    name: item.content
                });
            }
        });
    }
    // 报警设备
    getAllDevName() {
        if (this.stationId && this.devTypeId) {
            this.devTreeNodes = [];
            this.controlApiService.getDevByStationType(this.stationId, this.devTypeId).subscribe(res => {
                if (res.type === 'success') {
                    const data = res.response.data;
                    if (data.length) {
                        for (const item of data) {
                            this.devTreeNodes.push({
                                id: item.ID,
                                name: item.VC_NAME
                            });
                        }
                    }
                    this.devNameId = this.devTreeNodes[0].id;
                    this.devNameText = this.devTreeNodes[0].name;
                }
            });
        }
    } 
    themeChenge(e) {
        this.themeClass = e;
        switch (e) {
            case 'blacktheme':
                this.selectClass = 'controlSelect';
                this.tabBarStyle = { 'margin': '0 20px 5px 20px', 'text-align': 'center', 'color': '#fff' };
                break;
            case 'whitetheme':
                this.selectClass = 'defaultSelect';
                this.tabBarStyle = { 'margin': '0 20px 5px 20px', 'text-align': 'center', 'color': '#000' };
                break;
        }
    }
    // 报警类型值变化后查询数据
    alarmTypeChange(e) {
        setTimeout(() => {
            this.czjyAlarmType = this.alarmTypeId;
            // 设备检修记录表
            this.getWorkByDevName();
            // 设备问题记录表
            this.getProbByDevname();
            // 同类型报警案例表
            this.listByBjlx();
            // 设备历史故障信息表
            this.listByCz();
        }, 500);
    }
    // 报警设备值变化后查询数据
    devNameChange(e) {
        setTimeout(() => {
            // 反查设备类型
            this.getdevtype();
            // 设备检修记录表
            this.getWorkByDevName();
            // 设备问题记录表
            this.getProbByDevname();
            // 同类型报警案例表
            this.listByBjlx();
            // 设备历史故障信息表
            this.listByCz();
        }, 500);
    }
    getdevtype() {
        if (this.stationId == '' || this.devNameId == '') {
            return;
        }
        this.devNameText = this.devIdToName(this.devNameId);
        this.getDevnameType(this.stationId, this.devNameText).subscribe((res: any) => {
            if (res.pageList.length) {
                const type = res.pageList[0].DEVTYPE;
                this.devTypeId = type;
                // 报警类型
                this.getjcbjtype(this.devTypeId);
            }
        });
    }
    // 获取车站类型
    getDevnameType(id, name) {
        const url = environment.apiBase + '/csmis/publicpro/getdevtype.jwt?staid=' + id + '&devname=' + name;
        return this.http.get(url);
    }
    // 设备类型
    getAllTypesByStaId(stationId) {
        if (stationId == '') {
            return;
        }
        this.devTypeIf = false;
        this.devTypeSelect = [];
        this.devTypeId = '';

        this.statdevtype.getDevType(stationId, (resdata) => {
            this.devTypeIf = true;
            switch (resdata[0].children) {
                case undefined: case 'undefined': case null: case 'null': case false: case 'false':
                    this.devTypeId = resdata[0].id;
                    break;
                default:
                    this.devTypeId = resdata[0].children[0].id;
                    break;
            }
            this.devTypeSelect = this.treeTools.formatTreeNode(resdata);
            this.getjcbjtype(this.devTypeId);
            this.getAllDevName();
        });
    }
    // 报警类型
    getjcbjtype(devTypeId) {
        if (devTypeId == '') {
            return;
        }
        this.alarmTypeIf = false;
        this.alarmTypeSelect = [];
        this.alarmTypeId = '';

        this.statdevtype.getAlarmType(devTypeId, (resdata) => {
            this.alarmTypeIf = true;
            switch (resdata[0].children) {
                case undefined: case 'undefined': case null: case 'null': case false: case 'false':
                    this.alarmTypeId = resdata[0].id;
                    break;
                default:
                    this.alarmTypeId = resdata[0].children[0].id;
                    break;
            }
            this.alarmTypeSelect = this.treeTools.formatTreeNode(resdata);
            this.czjyAlarmType = this.alarmTypeId;
        });
    }
    // 设备检修记录表
    getWorkByDevName() {
        if (this.stationId == '' || this.devNameId == '') {
            return;
        }
        this.jxjlData = [];
        this.devNameText = this.devIdToName(this.devNameId);
        this.controlApiService.getWorkByDevName(this.stationId, this.devNameText).subscribe((res: any) => {
            for (const item of res) {
                this.jxjlData.push({
                    'time': this.datePipe.transform(item.DT_WORK$DAY, 'yyyy-MM-dd'),
                    'id': item.N_ID,
                    'type': item.VC_PROJECT,
                    'human': item.VC_WA$PERSON
                });
            }
        });
    }
    // 设备问题记录表
    getProbByDevname() {
        if (this.stationId == '' || this.devNameText == '') {
            return;
        }
        this.wtjlData = [];
        this.controlApiService.getProbByDevname(this.devNameText, this.stationId).subscribe((res: any) => {
            for (const item of res) {
                this.wtjlData.push({
                    'time': this.datePipe.transform(item.DT_SYS$DATE, 'yyyy-MM-dd'),
                    'id': item.N_ID,
                    'human': item.VC_USER,
                    'level': item.VC_LEVEL,
                    'desc': item.VC_PROBLEM
                });
            }
        });
    }
    // 同类型报警案例表
    listByBjlx() {
        if (this.alarmTypeId == '') {
            return;
        }
        this.bjalData = [];
        this.controlApiService.listByBjlx(this.alarmTypeId).subscribe((res: any) => {
            if (res.type === 'success') {
                const data = res.response.data;
                for (const item of data) {
                    this.bjalData.push({
                        'time': this.datePipe.transform(item.U_TIME * 1000, 'yyyy-MM-dd'),
                        'address': item.STATIONNAME,
                        'name': item.DEVNAME,
                        'info': item.ALARMTEXT,
                        'adv': item.CZJY
                    });
                }
            }
        });
    }
    // 设备历史故障信息表
    listByCz() {
        if (this.stationId == '' || this.devNameId == '') {
            return;
        }
        // if (this.automatic) {
        this.devNameText = this.devIdToName(this.devNameId);
        // }
        this.controlApiService.listByCz(this.stationId, this.devNameText).subscribe((res: any) => {
            if (res.type === 'success') {
                const data = res.response.data;
                if (data.length) {
                    for (const item of data) {
                        this.gzxxData.push({
                            'time': this.datePipe.transform(item.U_TIME * 1000, 'yyyy-MM-dd'),
                            'address': item.STATIONNAME,
                            'name': item.DEVNAME,
                            'info': item.ALARMTEXT,
                            'adv': item.CZJY
                        });
                    }
                }
            }
        });
    }
    onOk(result: Date): void {
        this.sjNameText = this.datePipe.transform(result, 'yyyy-MM-dd HH:mm:ss');
        const beginDate = this.datePipe.transform(new Date(this.sjNameText).getTime() - 1 * 15 * 60 * 1000, 'yyyy-MM-dd HH:mm:ss');
        const endDate = this.datePipe.transform(new Date(this.sjNameText).getTime() + 1 * 10 * 60 * 1000, 'yyyy-MM-dd HH:mm:ss');
        this.mnlIframe = this.sanitizer.bypassSecurityTrustHtml(
            '<iframe src="/csmis/staht/HTtest.jsp?setZoom=1.5&staId=' +
            this.stationId + '&beginDate=' + beginDate + '&endDate=' + endDate +
            '" frameborder="0" style="width:1876px;height:610px;position:absolute;z-index:9"></iframe>'
        );
    }
    stationChange(e) {
        setTimeout(() => {
            this.sjNameText = this.datePipe.transform(new Date(), 'yyyy-MM-dd HH:mm:ss');
            const beginDate = this.datePipe.transform(new Date(this.sjNameText).getTime() - 1 * 15 * 60 * 1000, 'yyyy-MM-dd HH:mm:ss');
            const endDate = this.datePipe.transform(new Date(this.sjNameText).getTime() + 1 * 10 * 60 * 1000, 'yyyy-MM-dd HH:mm:ss');
            this.mnlIframe = this.sanitizer.bypassSecurityTrustHtml('<iframe src="/csmis/staht/HTtest.jsp?setZoom=1.5&staId=' + e + '&beginDate=' + beginDate + '&endDate=' + endDate + '" frameborder="0" style="width:1876px;height:610px;position:absolute;z-index:9"></iframe>');
            this.getAllTypesByStaId(e);
            this.getAllDevName();
        }, 500);
    }
    devTypeChange(e) {
        setTimeout(() => {
            this.getWorkByDevName();
            this.getjcbjtype(e);
            this.getProbByDevname();
            this.getAllDevName();
            this.listByBjlx();
        }, 500);
    }
    command() {
        this.apiService.getorgstatree().subscribe((response: any) => {
            if (response.length) {
                let devNameId = '';
                if (this.devNameId && this.devNameId) {
                    devNameId = this.devNameId;
                }
                if (this.devNameText == '') {
                    this.message.error('请输入报警设备', { nzDuration: 1000 });
                    return false;
                }
                this.statdevtype.FindIdText('station', 'id', '', this.stationId, this.devTypeId, (resdata) => {
                    this.queryParams.STATIONNAME = resdata.text;

                    this.router.navigate(['control/command'], {
                        queryParams: {
                            'STATIONID': this.stationId,
                            'STATIONNAME': resdata.text,
                            'TIME': this.sjNameText,
                            'ALARMTYPE': this.alarmTypeId,
                            'ALARMTEXT': this.alarmKeyToTitle(this.alarmTypeId),
                            'DEVNAMEID': devNameId,
                            'DEVNAME': encodeURI(encodeURI(this.devNameText)),
                            'DEVTYPE': '',
                            'DEVTYPEID': this.devTypeId,
                            'ALARMDESCRIPTION': this.stepNameId
                        }
                    });

                    // const params = '?STATIONID=' + this.stationId +
                    //     '&STATIONNAME=' + resdata.text +
                    //     '&TIME=' + this.sjNameText +
                    //     '&ALARMTYPE=' + this.alarmTypeId +
                    //     '&ALARMTEXT=' + this.alarmKeyToTitle(this.alarmTypeId) +
                    //     '&DEVNAMEID=' + devNameId +
                    //     '&DEVNAME=' + encodeURI(encodeURI(this.devNameText)) +
                    //     '&DEVTYPE=' +
                    //     '&DEVTYPEID=' + this.devTypeId +
                    //     '&ALARMDESCRIPTION=' + this.stepNameId;
                    // window.open(environment.outLink + '/#/control/command' + params, '_blank');
                });
            }
        });
    }
    devIdToName(id) {
        let name = '';
        for (const item of this.devTreeNodes) {
            if (item.id == id) {
                name = item.name;
                break;
            }
        }
        return name;
    }
    alarmKeyToTitle(key) {
        let title = '';
        this.alarmTypeSelect.forEach((item, index) => {
            if (item.children) {
                for (const list of item.children) {
                    if (list.key == key) {
                        title = list.title;
                        break;
                    }
                }
            } else {
                if (this.devTreeNodes[index].key == key) {
                    title = this.devTreeNodes[index].title;
                }
            }
        });
        title = encodeURI(encodeURI(title));
        return title;
    }
}
